package at.bherbst;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UDPSensorActivity extends Activity  {

	private static final String TAG = "UDPSensorActivity";

	private Button applyButton;
	private Button startButton;
	private Button stopButton;
	private EditText text;

	private static SharedPreferences settings;
	private static SharedPreferences.Editor editor;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		settings = this.getSharedPreferences("udpserver",MODE_WORLD_WRITEABLE);
		//get value
		//will return "0" if preference not exists, else return stored value
		String val = settings.getString("serverip", "192.168.43.2");
		Toast.makeText(this, "loaded " + val, Toast.LENGTH_LONG).show();
		text = (EditText) this.findViewById(R.id.editText1);
		text.setText(val);
		
		
		applyButton = (Button) this.findViewById(R.id.button1);
		applyButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				updateText();
			}});
		
		startButton = (Button) this.findViewById(R.id.buttonStart);
		startButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startButton.setEnabled(false);
				Log.d(TAG, "onClick: starting srvice");
				startService(new Intent(UDPSensorActivity.this, UDPSenderService.class));
				stopButton.setEnabled(true);
			}
		});
		stopButton = (Button) this.findViewById(R.id.buttonStop);
		stopButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				stopButton.setEnabled(false);
				Log.d(TAG, "onClick: stopping srvice");
				stopService(new Intent(UDPSensorActivity.this, UDPSenderService.class));
				startButton.setEnabled(true);
			}
		});
	}
	
	private void updateText(){

			editor = settings.edit();
			//store value
			editor.putString("serverip", text.getText()+"");
			editor.commit();
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);
	    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

}